const db = require('../model/db');

// 添加商品到购物车
const addToCart = (req, res) => {
    const userId = req.user.id;
    const { product_id, pet_id, quantity = 1 } = req.body;

    if (!product_id && !pet_id) {
        return res.status(400).json({ error: '必须提供商品ID或宠物ID' });
    }

    if (product_id && pet_id) {
        return res.status(400).json({ error: '不能同时添加商品和宠物' });
    }

    // 检查商品/宠物是否存在且可购买
    const checkItem = () => {
        return new Promise((resolve, reject) => {
            if (product_id) {
                db.get('SELECT * FROM products WHERE id = ? AND status = "active" AND stock >= ?',
                    [product_id, quantity],
                    (err, product) => {
                        if (err) reject(err);
                        if (!product) reject(new Error('商品不存在或库存不足'));
                        resolve();
                    });
            } else {
                db.get('SELECT * FROM pets WHERE id = ? AND status = "available"',
                    [pet_id],
                    (err, pet) => {
                        if (err) reject(err);
                        if (!pet) reject(new Error('宠物不存在或已售出'));
                        resolve();
                    });
            }
        });
    };

    // 检查购物车是否已存在该商品/宠物
    const checkExisting = () => {
        return new Promise((resolve, reject) => {
            const query = 'SELECT * FROM cart_items WHERE user_id = ? AND ' +
                (product_id ? 'product_id = ?' : 'pet_id = ?');
            const params = [userId, product_id || pet_id];

            db.get(query, params, (err, item) => {
                if (err) reject(err);
                resolve(item);
            });
        });
    };

    // 执行添加或更新操作
    checkItem()
        .then(() => checkExisting())
        .then((existingItem) => {
            if (existingItem) {
                // 更新数量
                const newQuantity = existingItem.quantity + quantity;
                db.run(
                    'UPDATE cart_items SET quantity = ? WHERE id = ?',
                    [newQuantity, existingItem.id],
                    (err) => {
                        if (err) {
                            return res.status(500).json({ error: '更新购物车失败' });
                        }
                        res.json({ message: '购物车更新成功' });
                    }
                );
            } else {
                // 添加新项目
                const query = `INSERT INTO cart_items (user_id, product_id, pet_id, quantity) 
                             VALUES (?, ?, ?, ?)`;
                db.run(
                    query,
                    [userId, product_id, pet_id, quantity],
                    function(err) {
                        if (err) {
                            return res.status(500).json({ error: '添加到购物车失败' });
                        }
                        res.status(201).json({
                            message: '成功添加到购物车',
                            id: this.lastID
                        });
                    }
                );
            }
        })
        .catch((error) => {
            res.status(400).json({ error: error.message });
        });
};

// 获取购物车列表
const getCart = (req, res) => {
    const userId = req.user.id;
    console.log('Getting cart for user:', userId); // 添加日志

    // 首先验证用户是否存在
    db.get('SELECT id FROM users WHERE id = ?', [userId], (err, user) => {
        if (err) {
            console.error('验证用户失败:', err);
            return res.status(500).json({ error: '验证用户失败' });
        }
        if (!user) {
            console.error('用户不存在:', userId);
            return res.status(404).json({ error: '用户不存在' });
        }

        // 先获取购物车项
        const cartQuery = 'SELECT * FROM cart_items WHERE user_id = ?';
        console.log('Executing cart query:', cartQuery);
        console.log('With params:', [userId]);

        db.all(cartQuery, [userId], (err, cartItems) => {
            if (err) {
                console.error('获取购物车项失败:', err);
                return res.status(500).json({ error: '获取购物车失败' });
            }

            console.log('Raw cart items:', cartItems);

            if (!cartItems || cartItems.length === 0) {
                console.log('No items in cart');
                return res.json([]);
            }

            // 获取所有相关的商品和宠物信息
            const productIds = cartItems.filter(item => item.product_id).map(item => item.product_id);
            const petIds = cartItems.filter(item => item.pet_id).map(item => item.pet_id);

            console.log('Product IDs:', productIds);
            console.log('Pet IDs:', petIds);

            // 获取商品信息
            const getProducts = () => {
                if (productIds.length === 0) return Promise.resolve([]);
                return new Promise((resolve, reject) => {
                    const query = 'SELECT * FROM products WHERE id IN (' + productIds.map(() => '?').join(',') + ')';
                    db.all(query, productIds, (err, products) => {
                        if (err) reject(err);
                        else resolve(products);
                    });
                });
            };

            // 获取宠物信息
            const getPets = () => {
                if (petIds.length === 0) return Promise.resolve([]);
                return new Promise((resolve, reject) => {
                    const query = 'SELECT * FROM pets WHERE id IN (' + petIds.map(() => '?').join(',') + ')';
                    db.all(query, petIds, (err, pets) => {
                        if (err) reject(err);
                        else resolve(pets);
                    });
                });
            };

            // 并行获取商品和宠物信息
            Promise.all([getProducts(), getPets()])
                .then(([products, pets]) => {
                    console.log('Products:', products);
                    console.log('Pets:', pets);

                    // 创建商品和宠物的查找映射
                    const productMap = products.reduce((map, product) => {
                        map[product.id] = product;
                        return map;
                    }, {});

                    const petMap = pets.reduce((map, pet) => {
                        map[pet.id] = pet;
                        return map;
                    }, {});

                    // 处理购物车项
                    const processedItems = cartItems.map(item => {
                        if (item.product_id && productMap[item.product_id]) {
                            const product = productMap[item.product_id];
                            return {
                                id: item.id,
                                quantity: item.quantity,
                                created_at: item.created_at,
                                item: {
                                    type: 'product',
                                    id: product.id,
                                    name: product.name,
                                    price: product.price,
                                    image_url: product.image_url,
                                    status: product.status,
                                    stock: product.stock
                                }
                            };
                        } else if (item.pet_id && petMap[item.pet_id]) {
                            const pet = petMap[item.pet_id];
                            return {
                                id: item.id,
                                quantity: item.quantity,
                                created_at: item.created_at,
                                item: {
                                    type: 'pet',
                                    id: pet.id,
                                    name: pet.name,
                                    price: pet.price,
                                    image_url: pet.image_url,
                                    status: pet.status
                                }
                            };
                        }
                        return null;
                    }).filter(item => item !== null);

                    console.log('Processed cart items:', processedItems);
                    res.json(processedItems);
                })
                .catch(err => {
                    console.error('处理购物车数据失败:', err);
                    res.status(500).json({ error: '获取购物车失败' });
                });
        });
    });
};

// 更新购物车商品数量
const updateCartItem = (req, res) => {
    const userId = req.user.id;
    const { id } = req.params;
    const { quantity } = req.body;

    if (!quantity || quantity < 1) {
        return res.status(400).json({ error: '无效的数量' });
    }

    // 首先检查购物车项是否属于当前用户
    db.get(
        'SELECT * FROM cart_items WHERE id = ? AND user_id = ?',
        [id, userId],
        (err, item) => {
            if (err) {
                return res.status(500).json({ error: '查询购物车失败' });
            }
            if (!item) {
                return res.status(404).json({ error: '购物车项不存在' });
            }

            // 如果是商品，检查库存
            if (item.product_id) {
                db.get(
                    'SELECT stock FROM products WHERE id = ?',
                    [item.product_id],
                    (err, product) => {
                        if (err) {
                            return res.status(500).json({ error: '查询商品库存失败' });
                        }
                        if (!product || product.stock < quantity) {
                            return res.status(400).json({ error: '商品库存不足' });
                        }

                        updateQuantity();
                    }
                );
            } else {
                updateQuantity();
            }
        }
    );

    const updateQuantity = () => {
        db.run(
            'UPDATE cart_items SET quantity = ? WHERE id = ? AND user_id = ?',
            [quantity, id, userId],
            function(err) {
                if (err) {
                    return res.status(500).json({ error: '更新购物车失败' });
                }
                res.json({ message: '购物车更新成功' });
            }
        );
    };
};

// 从购物车中删除商品
const removeFromCart = (req, res) => {
    const userId = req.user.id;
    const { id } = req.params;

    db.run(
        'DELETE FROM cart_items WHERE id = ? AND user_id = ?',
        [id, userId],
        function(err) {
            if (err) {
                return res.status(500).json({ error: '删除购物车项失败' });
            }
            if (this.changes === 0) {
                return res.status(404).json({ error: '购物车项不存在' });
            }
            res.json({ message: '成功从购物车中删除' });
        }
    );
};

// 清空购物车
const clearCart = (req, res) => {
    const userId = req.user.id;

    db.run(
        'DELETE FROM cart_items WHERE user_id = ?',
        [userId],
        function(err) {
            if (err) {
                return res.status(500).json({ error: '清空购物车失败' });
            }
            res.json({ message: '购物车已清空' });
        }
    );
};

module.exports = {
    addToCart,
    getCart,
    updateCartItem,
    removeFromCart,
    clearCart
}; 